<?php
/**
 * Translateone Controller for yos_translator Component
 * @package		yos_translator
 * @subpackage	Components
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
jimport('joomla.filesystem.file');

/**
 * Translator Extension Controller
 *
 * @package		yos_translator
 * @subpackage	Components
 */
class FVBControllerJobs extends FVBController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

		$this->registerTask('new', 'edit');
		$this->registerTask('apply', 'save');
		$this->registerTask('unpublish', 'publish');
	}
	function edit(){
		$document 	= &JFactory::getDocument();
		$vType		= $document->getType();
		$vLayout 	= 'edit';
		$mName		= 'jobmanager';
		// Get/Create the view
		$view = &$this->getView( 'jobmanager', $vType);	
		JRequest::setVar( 'hidemainmenu', 1 );
		if ($model = &$this->getModel($mName)) {			
			$view->setModel($model, true);
		}
		// Set the layout
		$view->setLayout($vLayout);
		$view->edit();
	}

	function save(){
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db		 		= &JFactory::getDBO();
		$user			= &JFactory::getUser();
		$post			= JRequest::get( 'post' );
		// Set the table directory
		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
		$row =& JTable::getInstance('FVB_crawler_jobs','Table');
		$id	=	JRequest::getInt('cid');	
		if ($id) {
			$row->load($id);
		}

		$row->id=	JRequest::getInt('cid');
		if (!$row->bind( $post)) {
			JError::raiseError(500, $row->getError() );
		}
		
		$params		= JRequest::getVar( 'params', null, 'post', 'array' );
		
		if (is_array($params))
		{
			$txt = array ();			
			if (isset($params['keysave'])) {
				$keysave=$params['keysave'];
				$keysave=str_replace("\n",'\n',$keysave);
				$params['keysave']=$keysave;
			}			
			foreach ($params as $k => $v) {
				$txt[] = "$k=$v";
			}
			$row->params = implode("\n", $txt);
		}
		
		if(JRequest::getVar('trans')==null)
		{
			$row->t_from="";
			$row->t_to="";
		}	
		if (!$row->store()) {
			JError::raiseError(500, $row->getError() );
		}
		
		$row->checkin();

		switch ( JRequest::getCmd('task') )
		{
			case 'jobs.apply':
				$msg = JText::_( 'Changes to Job saved' );
				$tab_active=JRequest::getVar('tab_active');
				$mainframe->redirect( "index.php?option=".$post['option']."&task=jobs.edit&cid[]=". $row->id."&tab_active=$tab_active", $msg );
				break;

			case 'jobs.save':
			default:
				$msg = JText::_( 'Job saved' );				
				$mainframe->redirect( "index.php?option=".$post['option']."&task=jobmanager", $msg );
				break;
		}
	}
	function cancel(){
		global $mainframe,$option;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db =& JFactory::getDBO();

		// Set the table directory
		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
		$row =& JTable::getInstance('FVB_crawler_jobs','Table');
		
		$cid=JRequest::getVar('cid');
		$row->load($cid);
		
		$row->checkin();
		$mainframe->redirect( "index.php?option=$option&task=jobmanager" );
	}

	function remove(){
		global $mainframe, $option;
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db 	=& JFactory::getDBO();
		$cid 	= JRequest::getVar('cid', array(0), 'post', 'array');
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select a Link to delete', true ));
		}

		$cids = implode( ',', $cid );

		if (count( $cid )) {
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__FVB_crawler_jobs'
			. ' WHERE id IN ( '.$cids.' )'
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseError( 500, $db->stderr() );
				return false;
			}
		}

		$mainframe->redirect( "index.php?option=$option&task=jobmanager" );
	}
	function publish()
	{
		global $mainframe, $option;
		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
		$row =& JTable::getInstance('FVB_crawler_jobs','Table');
		$cids 	= JRequest::getVar('cid', array(0), 'post', 'array');
		$err=0;
		$user=JFactory::getUser();
		$task=JRequest::getVar('task');
		foreach ($cids as $cid)
		{
			$row->load($cid);
			if ( JTable::isCheckedOut($user->get ('id'), $row->checked_out )) {
				$err++;
				continue;
			}			
			$row->published= ($task=='jobs.publish')?1:0;		
			$row->store();
		}
		$sucses=count($cids)-$err;
		$mess="";
		$task=explode('.',$task);
		if($sucses)
			$mess.=$sucses.' '.JText::_('job(s) successfully '.$task[1]).". &nbsp; ";
		if ($err)
			$mess.=$err.' '.JText::_('job(s) is being edited by another administrator');
		
		$mainframe->redirect( "index.php?option=$option&task=jobmanager" ,$mess);
	}
	function overwritedata(){
		global $mainframe;
		
		$database = JFactory::getDBO();
		/* drop tables */
		$query = "DROP TABLE IF EXISTS `#__FVB_crawler`";
		$database->setQuery($query);
		$database->query();
		if ($database->getErrorNum()) {
			echo $database->getErrorMsg();
			return false;
		}	
		
		/* drop tables */
		$query = "DROP TABLE IF EXISTS `#__yos_content_link`";
		$database->setQuery($query);
		$database->query();
		if ($database->getErrorNum()) {
			echo $database->getErrorMsg();
			return false;
		}	

		if (!$result = YOSCreateDB::create()) {
			$mainframe->redirect(JRoute::_('index.php?option=com_feed_manager'), 'Can\'t create database');
			return ;
		}

		$mainframe->redirect(JRoute::_('index.php?option=com_feed_manager'), 'Clean database successful');
		return ;
	}
	/**
	 * ajax. get cms config
	 *
	 */
	function getCms_config_job()
	{
		$model=$this->getModel('jobmanager');

		$cms_name="";
		$cms_config=$model->getCms_config_job($cms_name);		
		if($cms_config)
		{				
			if ($cms_config->getNumParams()) {
				echo '<fieldset><legend>Config cms: </legend>';		
					echo $cms_config->render('pamras');
				echo '</fieldset>';
			}			
			$gr=$cms_config->getGroups();				
			foreach ($gr as $k=>$value)
			{
				if(!$value or $k=='_default')
					continue;
					
				echo '<fieldset><legend>'.preg_replace('/[_-]/',' ',$k).': </legend>';
				echo $cms_config->render('params',$k);
				echo '</fieldset>';
			}				
		}
		else {
			echo JText::_('Not found cms config xml file');
		}	
		die();
	}
	function resetErr()
	{
		$model=$this->getModel('jobmanager');
		$model->resetErr();
		die();
	}
	function actionCms()
	{
		$cms	=	JRequest::getVar('cms','joomla');
		$path	=	JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.$cms.DS.'action.php';
		if (JFile::exists($path)) {
			require_once($path);
			$class_name	=	'action'.ucfirst($cms);
			$cms_class	=	new $class_name();
			$str	=	$cms_class->action();
			echo $str;
		}
		die();
	}
}